/**
 * Logic for ideaList.html
 */

window.fbAsyncInit = function() {
	FB.init({
		appId      : '313149895398128', // App ID
		channelUrl : 'http://gemeinde-in-aktion.appspot.com/channel.html', // Channel File
		status     : true, // check login status
		cookie     : true, // enable cookies to allow the server to access the session
		xfbml      : true  // parse XFBML
	});

	FB.getLoginStatus(function(response) {
		if (response.status === 'connected') {
			var uid = response.authResponse.userID;
			var accessToken = response.authResponse.accessToken;

			$('#fbLoginInfo').attr('accessToken', accessToken);

			$.getJSON("/users", {
				action: "getUsers",
				accessToken: $('#fbLoginInfo').attr('accessToken')
			}, function(data){         
				buildUserList(data);
			});

			FB.api('/me', function(user) {
				if (user) {
					var image = document.getElementById('fbimage');
					image.src = 'https://graph.facebook.com/' + user.id + '/picture';
					var name = document.getElementById('fbname');
					name.innerHTML = user.name;
					$('#fbLoginInfo').attr('userId', user.id);
				}
			});
		} else if (response.status === 'not_authorized') {
			// the user is logged in to Facebook, 
			//but not connected to the app
			alert("not authorized");
		} else {
			// the user isn't even logged in to Facebook.
			alert("not logged in");
		}
	});
};

// Load the SDK Asynchronously
(function(d){
	var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
	js = d.createElement('script'); js.id = id; js.async = true;
	js.src = "//connect.facebook.net/en_US/all.js";
	d.getElementsByTagName('head')[0].appendChild(js);
}(document));

function buildUserList(data){
	$("#userList").empty();

	if(data.isAuthenticated==" "){
		var errorMsg = "<p>nicht authentifiziert</p>";
		$("#userList").append(errorMsg);
	}

	$.each(data.users, function(i,user){
		var newItem = '<div><b>' + user.email + '</b>';
		newItem += '<span>' + user.status + ';</span>';
		var userName = user.name;
		if(userName===""){userName="kein Name bekannt";}
		newItem += '<span>' + userName + ';</span>';
		var fbId = user.fbId;
		if(fbId==""){fbId="keine fbId bekannt";}
		newItem += '<span>' + fbId + ';</span>';

//		if(user.status!="1"){
			newItem += '<a href="#" class="deleteAction ui-state-default ui-corner-all" data-id="'+user.email+'" fbId="' + user.fbId + '">delete</a>';
			newItem += '<a href="#" class="authorizeAction ui-state-default ui-corner-all" data-id="'+user.email+'" fbId="' + user.fbId + '">authorize</a>';
//		}
		newItem += '</div>';
		$("#userList").append(newItem);
	});

	$(".authorizeAction").click(function(ev){
		$.post("/users", {
			action: "authorize",
			accessToken: $('#fbLoginInfo').attr('accessToken'),
			email: $(this).attr("data-id"),
			fbId: $(this).attr("fbId")
		}, function(data){         
//			alert("user authorized");
		});
	});

	$(".deleteAction").click(function(ev){
		$.post("/users", {
			action: "delete",
			accessToken: $('#fbLoginInfo').attr('accessToken'),
			email: $(this).attr("data-id"),
            fbId: $(this).attr("fbId")
		}, function(data){         
//			alert("user deleted");
		});
	});

};

$(document).ready(function(){
	$("#addUser").click(function(ev){
		$.post("/users", {
			action: "addUser",
			accessToken: $('#fbLoginInfo').attr('accessToken'),
			email: $("#emailForm").val()
		}, function(data){         
			alert("user added");
			$("#emailForm").val("");
		});
	});
	
	$("#newPasswordButton").click(function(ev){
		$.post("/users", {
			action: "newPassword",
			accessToken: $('#fbLoginInfo').attr('accessToken'),
			password: $("#passwordForm").val()
		}, function(data){         
			alert("password changed");
			$("#emailForm").val("");
		});
	});
});